/**
 *  Copyright 2006-2007 EmbedChat
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.embedchat.desktop.client;

import java.util.List;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.embedchat.desktop.StateModel;
import org.embedchat.protocol.message.common.TextMessage;
import org.embedchat.protocol.message.server.ErrorMessage;
import org.embedchat.protocol.message.server.RoomsListMessage;
import org.embedchat.protocol.message.server.UsersListMessage;
import org.embedchat.protocol.message.server.RoomsListMessage.RoomDescription;
import org.embedchat.protocol.message.server.UsersListMessage.UserDescription;

public class ClientSessionHandler extends IoHandlerAdapter {

	private final Logger log = LoggerFactory.getLogger(ClientSessionHandler.class);	
	private StateModel model;

	public ClientSessionHandler(StateModel model) {
		this.model = model;
	}

    public void messageReceived(IoSession session, Object message) {
    	if(ErrorMessage.class.equals(message.getClass())) {
    		ErrorMessage eMessage = (ErrorMessage) message;
        	model.setErrorMessage(eMessage.getErrorMessageString());
        	model.setRequestForError(true);
        	model.update();
        	
    	} else if (RoomsListMessage.class.equals(message.getClass())) {
    		RoomsListMessage rMessage = (RoomsListMessage) message;
    		List<RoomDescription> rooms = rMessage.getRooms();
    		model.setRooms(rooms);
    		model.changeState(StateModel.CONNECTION_ESTABLISHED_STATE);
			
    	} else if (UsersListMessage.class.equals(message.getClass())) {
    		UsersListMessage uMessage = (UsersListMessage) message;
    		model.setRoomUsers(uMessage.getUsers());
    		model.changeState(StateModel.USER_LOGGED_STATE);    		
    		
    	} else if (TextMessage.class.equals(message.getClass())) {
    		TextMessage tMessage = (TextMessage) message;
    		List<UserDescription> users = model.getRoomUsers();
    		for (UserDescription description : users) {
				if (description.getUserId() == tMessage.getUserId()) {
					model.setReceivedMessageAuthor(description.getUserName());
		    		model.setReceivedMessage(tMessage.getMessageString());
		    		model.setRequestForShowMessage(true);
				}
			}
    		
    	} else {
    		log.debug("messageReceived: " + message);
    	}
    	
    	model.update();
    }

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		log.debug("session closed: " + session);
		model.changeState(StateModel.DISCONNECTED_STATE);		
		model.update();
		super.sessionClosed(session);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable exception) throws Exception {
		exception.printStackTrace();
		log.debug("exceptionCaught: " + session);
		model.changeState(StateModel.DISCONNECTED_STATE);		
		model.update();
//		super.exceptionCaught(session, exception);
	}	
	
	
}
